import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { User } from 'src/user/entities/user.entity'
import { Repository } from 'typeorm'
import { UpdateNoteDto } from './dto/update-note.dto'
import { Note } from './entities/note.entity'

@Injectable()
export class NoteService {
  constructor(
    @InjectRepository(Note) private readonly note: Repository<Note>,
    @InjectRepository(User) private readonly user: Repository<User>
  ) {}
  // 新增笔记
  async create(body, req) {
    const userId = req.session.user_id

    // 用户对应的笔记
    const user_data = await this.user.findOne({ relations: ['note'], where: { _id: userId } })

    const note = new Note()
    note.title = body.title
    note.content = body.content

    await this.note.save(note)

    const user_note = user_data.note

    user_data.note = [...user_note, note]

    await this.user.save(user_data)

    return '新增成功'
  }

  // 获取改用户的所有笔记
  async findAll(req, query) {
    const userId = req.session.user_id

    const user_data = await this.user.findOne({ relations: ['note'], where: { _id: userId } })

    // 计算起始索引
    const startIndex = (query.pageNo - 1) * query.pageSize
    // 计算结束索引
    const endIndex = startIndex + parseInt(query.pageSize)

    const notes = user_data.note.slice(startIndex, endIndex)

    // 前端的table要指定一个id
    const handle_notes = notes.map(item => {
      return {
        ...item,
        id: item._id
      }
    })

    return { count: user_data.note.length, data: [...handle_notes] }
  }

  findOne(id: number) {
    return `This action returns a #${id} note`
  }

  // 更新笔记
  async update(id: number, updateNoteDto: UpdateNoteDto) {
    await this.note.update(id, updateNoteDto)
    return `更新成功`
  }

  // 删除笔记
  async remove(id: number) {
    await this.note.delete(id)
    return `删除笔记成功`
  }
}
